package com.bwda.dsrs.systemservice.controller;


import com.bwda.dsrs.base.centerbase.BaseConstants;
import com.bwda.dsrs.base.centerbase.BaseContextHandler;
import com.bwda.dsrs.base.centerbase.condition.BaseCondition;
import com.bwda.dsrs.base.centerbase.form.BaseQueryForm;
import com.bwda.dsrs.base.centerbase.request.BaseQueryRequest;
import com.bwda.dsrs.base.centerbase.response.CentreCutPageResponse;
import com.bwda.dsrs.base.centerbase.response.CentreListResponse;
import com.bwda.dsrs.base.centerbase.response.ResponseEntity;
import com.bwda.dsrs.base.util.StringUtil;
import com.bwda.dsrs.systemservice.domain.exception.SystemServiceException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.json.JsonParseException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @author yangjun
 * @date 2019/4/18
 */
public class BaseController {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     * 业务异常控制
     *
     * @param e
     * @return
     */
    @ExceptionHandler(SystemServiceException.class)
    public
    @ResponseBody
    ResponseEntity bwdaExceptionHandler(SystemServiceException e) {
        logger.warn(e.getLocalizedMessage());
        return this.getFailResult(e.getErrCode(), e.getMessage());
    }

    /**
     * 运行期异常控制
     *
     * @param e
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public
    @ResponseBody
    ResponseEntity runtimeExceptionHandler(RuntimeException e) {
        logger.error("发生系统异常", e);
        return this.getFailResult("系统异常，请和管理员联系！");
    }

    @ExceptionHandler({BindException.class})
    public ResponseEntity bindExceptionHandler(BindException e) {
        this.logger.warn(e.getLocalizedMessage());
        return this.getFailResult(Objects.requireNonNull(e.getFieldError()).getDefaultMessage());
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public ResponseEntity methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        this.logger.warn(e.getLocalizedMessage());
        return this.getFailResult(Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage());
    }

    @ExceptionHandler({Exception.class})
    public ResponseEntity exceptionHandler(Exception e) {
        if (e instanceof JsonParseException) {
            this.logger.warn("请求体json转化出错", e);
            return this.getFailResult("请求体json转化出错");
        } else if (e instanceof HttpMediaTypeNotSupportedException) {
            this.logger.warn("http媒体类型不支持异常", e);
            return this.getFailResult("http媒体类型不支持异常:" + e.getMessage());
        } else if (e instanceof MissingServletRequestParameterException) {
            this.logger.warn("缺少参数", e.getLocalizedMessage());
            return this.getFailResult("缺少参数:" + e.getMessage());
        } else {
            this.logger.error("发生异常", e);
            return this.getFailResult("请求出错");
        }
    }

    protected <T> ResponseEntity<T> getSuccessResult(T obj) {
        return new ResponseEntity("ok", 200, "操作成功", obj);
    }

    protected ResponseEntity getSuccessResult(String msg) {
        return new ResponseEntity("ok", 200, msg, Collections.EMPTY_MAP);
    }

    protected <T> ResponseEntity<T> getSuccessResult(String msg, T obj) {
        return new ResponseEntity("ok", 200, msg, obj);
    }

    protected ResponseEntity getSuccessResult() {
        return this.getSuccessResult("操作成功");
    }

    protected ResponseEntity getFailResult(String msg) {
        return this.getFailResult(201, msg);
    }

    protected ResponseEntity getFailResult(int errCode, String msg) {
        return new ResponseEntity("fail", errCode, msg, null);
    }

    protected <T> CentreListResponse<T> getListResponse(List<T> dataList) {
        return new CentreListResponse(dataList);
    }

    protected <T> CentreCutPageResponse<T> getPageResponse(BaseQueryRequest queryRequest, long totalCount, List<T> dataList) {
        return new CentreCutPageResponse(queryRequest.getPageNum(), queryRequest.getPageSize(), totalCount, dataList);
    }

    protected <T> CentreCutPageResponse<T> getPageResponse(BaseCondition condition, long totalCount, List<T> dataList) {
        return new CentreCutPageResponse(condition.getPageNum(), condition.getPageSize(), totalCount, dataList);
    }

    protected <T> CentreCutPageResponse<T> getPageResponse(BaseQueryForm form, long totalCount, List<T> dataList) {
        return new CentreCutPageResponse(form.getPageNum(), form.getPageSize(), totalCount, dataList);
    }

    protected <T> CentreCutPageResponse<T> getPageResponse(int pageNum, int pageSize, long totalCount, List<T> dataList) {
        return new CentreCutPageResponse(pageNum, pageSize, totalCount, dataList);
    }


    public String getUserCode() throws SystemServiceException {
        String userCode = BaseContextHandler.getUserCode();
        if (StringUtils.isEmpty(userCode)) {
            throw new SystemServiceException(BaseConstants.RESCODE_NOT_LOGINED, "未登录");
        }
        return userCode;
    }

    public String getAuthorization() throws SystemServiceException {
        String token = BaseContextHandler.getAuthorization();
        if (StringUtils.isEmpty(token)) {
            throw new SystemServiceException(BaseConstants.RESCODE_NOT_LOGINED, "未登录");
        }
        return token;
    }


}

